from jdbcdao.iwapper import IWapper
from jdbcdao.iconnection import Iconnect

'''jdbc数据库操作模板'''


class JdbcTemplate(object):

    def __init__(self,iconnect:Iconnect):
        self.iconnect = iconnect

    def ddl(self, sql):
        conn = self.iconnect.get_connect()
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
        self.__close_conn(conn)

    def dml(self, sql):
        conn = self.iconnect.get_connect()
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
        self.__close_conn(conn)
        print("dml success")

    def dql(self, sql, wapper:IWapper) -> list:
        conn = self.iconnect.get_connect()
        cursor = conn.cursor()
        c = cursor.execute(sql)
        result_set = cursor.fetchall()
        datas = []
        for row in result_set:
            row_data = wapper.wapper(row)
            datas.append(row_data)
        self.__close_conn(conn)
        return datas

    def __close_conn(self,conn):
        self.iconnect.close_conncet(conn)